#include "TCPClient.h"
#include"Main/GateWay.h"
TCPClient::TCPClient(QObject *parent)
    : BasePort(parent)
{

    tcpClient = new QTcpSocket(this);
    connect(tcpClient, SIGNAL(connected()), this, SLOT(connectedSlot()));
    connect(tcpClient, SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));
    connect(tcpClient, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));

    reconnectTimer = new QTimer(this);
    reconnectTimer->setInterval(1000);
    connect(reconnectTimer, SIGNAL(timeout()), this, SLOT(timeoutSlot()));
    reconnectTimeout=0;

}

void TCPClient::setPortParam(PortStruct portParam)
{

    m_portParam = portParam;
    this->setObjectName(portParam.name());
}

void TCPClient::open()
{
    reconnectTimer->start();
}

void TCPClient::close()
{
    reconnectTimer->stop();
    tcpClient->disconnectFromHost();
}



void TCPClient::write(PortStruct target,QByteArray data)
{
    if(tcpClient->ConnectedState  == QAbstractSocket::ConnectedState)
    {
        QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd");
        tcpClient->write(data);

        qDebug()<<"Write-->"<<target<<"data:"<<DataTypeConver::formatString(data);
        Log::lock.lockForWrite();
        Log::writeToLog(time,"Write-->"+target.portName()+" data: "+DataTypeConver::formatString(data));
        Log::lock.unlock();

    }
}


void TCPClient::readyReadSlot()
{
    QByteArray data = tcpClient->readAll();
   QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd");

    qDebug()<<"Read<-- "<<m_portParam<<"data:"<<DataTypeConver::formatString(data);
    Log::lock.lockForWrite();
    Log::writeToLog(time,"Read<--"+m_portParam.portName()+"/"+m_portParam.name()+" data: "+DataTypeConver::formatString(data));
    Log::lock.unlock();

    qDebug()<<"TCP Client runing now";
    reconnectTimeout=0;
    emit receiveDataSignal(m_portParam,data);

}

void TCPClient::disconnectedSlot()
{
    qDebug()<<"TCPClient has disconnected";
    emit isConnectedSignal(false,m_portParam);
}

void TCPClient::connectedSlot()
{
    qDebug()<<"TCPClient has connected successful";
    emit isConnectedSignal(true,m_portParam);
}

void TCPClient::timeoutSlot()
{
    reconnectTimeout++;
    if((tcpClient->state() != QAbstractSocket::ConnectedState)||(reconnectTimeout>=180))
    {
        reconnectTimeout=0;
        tcpClient->abort();
        tcpClient->connectToHost(m_portParam.ip(),m_portParam.port());
    }
}


TCPClient::~TCPClient()
{

}
